package controller

import (
	"ginEssential/common"
	"ginEssential/model"
	"ginEssential/response"
	"ginEssential/vo"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"strconv"
)

type IPostController interface {
	RestController
	PageList(c*gin.Context) //分页功能
}
type PostController struct {
	DB *gorm.DB
}

func (p PostController) PageList(c *gin.Context) {
	//获取分页参数
	pageNum,_:=strconv.Atoi(c.DefaultQuery("pageNum","1")) //获取参数 ，默认为1
	pageSize,_:=strconv.Atoi(c.DefaultQuery("pageSize","5")) //获取参数 ，默认为5
	//分页
	var posts []model.Post
	p.DB.Order("created_at desc").Offset((pageNum-1)*pageSize).Limit(pageSize).Find(&posts)
	//前端需要知道的总数
	var total int
	p.DB.Model(model.Post{}).Count(&total)
	response.Success(c,gin.H{"data":posts,"total":total},"success")
}

func NewPostController() IPostController {
	db:=common.GetDB()
	db.AutoMigrate(&model.Post{})
	return PostController{DB: db}
}

func (p PostController) Create(c *gin.Context) {
	var requestPost   vo.CreatePostRequest
	//数据验证
	if err:=c.ShouldBind(&requestPost);err!=nil{
		response.Failed(c,nil,"数据验证错误")
		return
	}
	//获取登录用户 user
	user,_:=c.Get("user")

	//创建post
	post:=model.Post{
		UserId:     user.(model.User).ID,
		CategoryId:	requestPost.CategoryId,
		Title:      requestPost.Title,
		HeadImg:    requestPost.HeadImg,
		Content:    requestPost.Content,
	}
	if err:=p.DB.Create(&post).Error;err!=nil{
		panic(err)
		return
	}
	response.Success(c,nil,"创建成功")
}

func (p PostController) Update(c *gin.Context) {
	var requestPost   vo.CreatePostRequest
	//数据验证
	if err:=c.ShouldBind(&requestPost);err!=nil{
		response.Failed(c,nil,"数据验证错误")
		return
	}

	//获取路径中的postID
	postID:=c.Param("id")
	var post model.Post
	if p.DB.Where("id=?",postID).First(&post).RecordNotFound(){
		response.Failed(c,nil,"文章不存在")
		return
	}

	//获取登录用户 user 判断对当前用户是否为文章的作者
	user,_:=c.Get("user")
	userID:=user.(model.User).ID
	if userID!=post.UserId{
		response.Failed(c,nil,"文章不属于您 请勿非法操作")
	}
	//更新post
	if err:=p.DB.Model(&post).Update(requestPost).Error;err!=nil{
		response.Failed(c,nil,"更新失败")
		return
	}
	response.Success(c,gin.H{"post":post},"更新成功")
}

func (p PostController) Show(c *gin.Context) {
	//获取路径中的postID
	postID:=c.Param("id")
	var post model.Post
	if p.DB.Preload("Category").Where("id=?",postID).First(&post).RecordNotFound(){
		response.Failed(c,nil,"文章不存在")
		return
	}
	response.Success(c,gin.H{"post":post},"请求成功")
}

func (p PostController) Delete(c *gin.Context) {

	//获取路径中的postID
	postID:=c.Param("id")
	var post model.Post
	if p.DB.Where("id=?",postID).First(&post).RecordNotFound(){
		response.Failed(c,nil,"文章不存在")
		return
	}

	//获取登录用户 user 判断对当前用户是否为文章的作者
	user,_:=c.Get("user")
	userID:=user.(model.User).ID
	if userID!=post.UserId{
		response.Failed(c,nil,"文章不属于您 请勿非法操作")
	}
	//删除
	if err:=p.DB.Delete(&post).Error;err!=nil{
		response.Failed(c,nil,"删除失败")
		return
	}
	response.Success(c,nil,"删除成功")
}

